from time import sleep
from mousecolor import Ui_Form
from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel
from PyQt5.QtCore import QThread, pyqtSignal, Qt, QRect
from pyautogui import position
import sys
import imgvision as iv
import numpy as np

__support_platform__ = ["win32", "linux"]
__sys_platform__ = sys.platform

if __sys_platform__ in __support_platform__:
    if __sys_platform__ == "linux":
        import gi

        gi.require_version("Gdk", "3.0")
        from gi.repository import Gdk

        def get_color_lnx(x, y):
            w = Gdk.get_default_root_window()
            pb = Gdk.pixbuf_get_from_window(w, x, y, 1, 1)
            return list(tuple(pb.get_pixels()))

    elif __sys_platform__ == "win32":
        from ctypes import windll

        def get_color_win(x, y):
            gdi32 = windll.gdi32
            user32 = windll.user32
            hdc = user32.GetDC(None)  # 获取颜色值
            pixel = gdi32.GetPixel(hdc, x, y)  # 提取RGB值
            r = pixel & 0x0000FF
            g = (pixel & 0x00FF00) >> 8
            b = pixel >> 16
            return [r, g, b]


class Node:
    def __init__(self, data=None, next=None) -> None:
        self.data = data
        self.next = next

    def getdata(self):
        return self.data


class LinerTab:
    node_rgb = Node("RGB")
    node_lab = Node("LAB")
    node_hsv = Node("HSV")
    node_rgb.next = node_lab
    node_lab.next = node_hsv
    node_hsv.next = node_rgb
    size = 3
    _temp_node = node_rgb

    def getdata(self):
        self._temp_node = self._temp_node.next
        return self._temp_node.getdata()


class Thread(QThread):
    sig = pyqtSignal(list)

    def __init__(self):
        super(Thread, self).__init__()

    def run(self):
        while True:
            x, y = position()
            if __sys_platform__ == "win32":
                self.sig.emit(get_color_win(x, y))
            elif __sys_platform__ == "linux":
                self.sig.emit(get_color_lnx(x, y))
            else:
                print("Byebye!")
            sleep(0.1)


class MyQLabel(QLabel):
    button_clicked_signal = pyqtSignal()

    def __init__(self, parent=None):
        super(QLabel, self).__init__(parent)

    def mouseReleaseEvent(self, ev):
        self.button_clicked_signal.emit()

    def connect_customized_slot(self, func):
        self.button_clicked_signal.connect(func)


class MainWindow(Ui_Form, QMainWindow):
    cvtor = iv.cvtcolor()
    rotation_select_map = {
        "RGB": ["R", "G", "B"],
        "LAB": ["L", "a", "b"],
        "HSV": ["H", "S", "V"],
    }
    labelvalue = rotation_select_map.get("RGB")

    def __init__(self) -> None:
        super(Ui_Form, self).__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.lbl_author = MyQLabel(self)
        self.lbl_author.setGeometry(QRect(58, 50, 71, 21))
        self.lbl_author.setStyleSheet('font: 9pt "Eras Medium ITC";\n' "color: rgb(255, 0, 0);")
        self.lbl_author.setText("By AlexShiDi")
        self.lbl_author.connect_customized_slot(self.lbl_author_clicked)
        self.linertab = LinerTab()

        self.window_config()
        self.threadx = Thread()
        self.threadx.sig.connect(self.setColor)
        self.threadx.start()

    def window_config(self):
        self.setFixedSize(self.width(), self.height())
        self.setWindowFlags(Qt.WindowMaximizeButtonHint | Qt.WindowStaysOnTopHint |  Qt.WindowCloseButtonHint)

    def setColor(self, color):
        self.ui.tbcolor.setStyleSheet(f"background-color: rgb({color[0]}, {color[1]}, {color[2]});")
        if self.labelvalue == ["R", "G", "B"]:
            # RGB
            self.ui.lbl_color_r.setText(f"{color[0]}")
            self.ui.lbl_color_g.setText(f"{color[1]}")
            self.ui.lbl_color_b.setText(f"{color[2]}")
        elif self.labelvalue == ["L", "a", "b"]:
            # LAB
            color = self.rgb2lab(color[0], color[1], color[2])
            self.ui.lbl_color_r.setText(f"{color[0]}")
            self.ui.lbl_color_g.setText(f"{color[1]}")
            self.ui.lbl_color_b.setText(f"{color[2]}")
        else:
            # HSV
            color = self.rgb2hsv(color[0], color[1], color[2])
            self.ui.lbl_color_r.setText(f"{color[0]}")
            self.ui.lbl_color_g.setText(f"{color[1]}")
            self.ui.lbl_color_b.setText(f"{color[2]}")

    def lbl_author_clicked(self):
        self.labelvalue = self.rotation_select_map.get(self.linertab.getdata())
        self.ui.lbl_r.setText(self.labelvalue[0])
        self.ui.lbl_g.setText(self.labelvalue[1])
        self.ui.lbl_b.setText(self.labelvalue[2])

    def rgb2lab(self, xr=255, xg=255, xb=255):
        img = np.array([[[xr, xg, xb]]], dtype=np.float32)
        return self.cvtor.rgb2lab(img / 255).reshape(-1)

    def rgb2hsv(self, xr=255, xg=255, xb=255):
        img = np.array([[[xr, xg, xb]]], dtype=np.float32)
        return self.cvtor.rgb2hsv(img / 255).reshape(-1)


def main():
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()
